﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Insteon
{
    public class InsteonAddress
    {
        internal readonly byte High = 0;
        internal readonly byte Mid = 0;
        internal readonly byte Low = 0;

        public InsteonAddress(string address)
        {
            Regex X = new Regex(@"([0-9a-fA-F]{1,2})\.([0-9a-fA-F]{1,2})\.([0-9a-fA-F]{1,2})");
            if (!X.IsMatch(address))
            {
                throw new Exception("not a reconized insteon address");
            }
            Match Match = X.Match(address);
            if (Match.Groups.Count != 4)
            {
                throw new Exception("not a reconized insteon address");
            }
            High = (byte) Convert.ToInt16(Match.Groups[1].ToString(), 16);
            Mid = (byte)Convert.ToInt16(Match.Groups[2].ToString(), 16);
            Low = (byte)Convert.ToInt16(Match.Groups[3].ToString(), 16);
        }

        internal InsteonAddress(byte[] bytes)
        {
            if (bytes.Length < 3)
            {
                throw new Exception("Not a valid address");
            }
            High = bytes[0];
            Mid = bytes[1];
            Low = bytes[2];
        }
        internal InsteonAddress(byte[] bytes, int index)
        {
            if (bytes.Length < index + 3)
            {
                throw new Exception("Not a valid address");
            }
            High = bytes[index];
            Mid = bytes[index + 1];
            Low = bytes[index + 2];
        }
        public override string ToString()
        {
            return String.Format("{0:x2}.{1:x2}.{2:x2}", High, Mid, Low).ToUpper();
        }

        public static bool operator ==(InsteonAddress a, InsteonAddress b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(InsteonAddress a, InsteonAddress b)
        {
            return !a.Equals(b);
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            if (!(obj is InsteonAddress))
            {
                return false;
            }
            InsteonAddress o = (InsteonAddress)obj;
            if ((this.High == o.High) && (this.Mid == o.Mid) && (this.Low == o.Low))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            return (int) (High * 256 * 256) + (Mid * 256) + Low;
        }
    }
}
